/*
 * Copyright (C) 2009 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.yongnuo.remoteconlight;

import java.util.ArrayList;
import java.util.Set;
import java.util.UUID;


import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.yongnuo.support.FinalValue;
import com.yongnuo.support.ShowAdapter;

/**
 * This Activity appears as a dialog. It lists any paired devices and
 * devices detected in the area after discovery. When a device is chosen
 * by the user, the MAC address of the device is sent back to the parent
 * Activity in the result Intent.
 */
public class DeviceListActivity extends Activity {
    // Debugging
    private static final String TAG = "zbble";
    private static final boolean D = true;
    private boolean newDevicesListViewClickable = true;
    private boolean pariedDevicesListViewClickable = true;
    public boolean in = true;
    
    // Return Intent extra
    public static String EXTRA_DEVICE_ADDRESS = "device_address";

    // Member fields
    private BluetoothAdapter mBtAdapter;
    private ArrayList<String> mNewDevicesSet = new ArrayList<String>();
    private ShowAdapter mNadapter;
//    private ArrayAdapter<String> mNewDevicesArrayAdapter;

    private final int BLUETOOTH_SCAN_PERIOD = 10000;
    private Handler mHandler;
    private ProgressBar pb;
    private ImageButton back_Button;
    private TextView tv;
    private String scanning;
    private String choose;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Setup the window
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.device_list);
        
        pb = (ProgressBar) findViewById(R.id.progressBar_scan);
        pb.setVisibility(View.INVISIBLE);
        
        back_Button = (ImageButton) findViewById(R.id.button_back);
        back_Button.setOnClickListener(new OnClickListener() {
            
            @Override
            public void onClick(View arg0)
            {
                // TODO Auto-generated method stub
                if(ble_scanning)
                {
                    mBtAdapter.stopLeScan(mLeScanCallback);
                }

                Intent intent = new Intent();
                // Create the result Intent and include the MAC address
                if(HintActivity.isFirst){
                    intent.setClass(DeviceListActivity.this, RemoteActivity.class);
                    startActivity(intent);
                }else{
                    // Set result and finish this Activity
                    setResult(Activity.RESULT_CANCELED, intent);
                }
                finish(); 
            }
        });

        scanning = (String)getResources().getString(R.string.scanning);
        choose   = (String)getResources().getString(R.string.select_device);

        tv = (TextView) findViewById(R.id.textView_status);
        tv.setText(scanning);
        
        // Set result CANCELED in case the user backs out
        if(!HintActivity.isFirst){
        	setResult(Activity.RESULT_CANCELED);
        }

        // Initialize array adapters. One for already paired devices and
        // one for newly discovered devices
        mNadapter = new ShowAdapter(this,mNewDevicesSet);

        // Find and set up the ListView for newly discovered devices
        ListView newDevicesListView = (ListView) findViewById(R.id.new_devices);
        newDevicesListView.setAdapter(mNadapter);
        newDevicesListView.setOnItemClickListener(mDeviceClickListener);

        // Get the local Bluetooth adapter
        mBtAdapter = BluetoothAdapter.getDefaultAdapter();
        if (mBtAdapter == null) {
            Toast.makeText(this, R.string.bluetooth_is_not_available, Toast.LENGTH_LONG).show();
            finish();
            return;
        }
        
        mHandler = new Handler();
    }

    private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {

        @Override
        public void onLeScan(BluetoothDevice arg0, int arg1, byte[] arg2)
        {
            // TODO Auto-generated method stub
            // Get the BluetoothDevice object from the Intent
            BluetoothDevice device = arg0;
            // If it's already paired, skip it, because it's been listed already
            String name = device.getName() + "\n" + device.getAddress();
            if ((device.getType() == BluetoothDevice.DEVICE_TYPE_LE || device.getType() == BluetoothDevice.DEVICE_TYPE_UNKNOWN)     
                && !mNewDevicesSet.contains(name)) 
            {
                mNewDevicesSet.add(name);
                newDevicesListViewClickable = true;
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
        		// TODO Auto-generated method stub
                        mNadapter.setmSet(mNewDevicesSet);
                        mNadapter.notifyDataSetChanged();			
        	   }
                });
            }
            Log.d(TAG, "we found a ble device! = " + arg0.toString());
        }        

    };
    
    @Override
    protected void onStart() {
    	// TODO Auto-generated method stub
    	super.onStart();
        if (!mBtAdapter.isEnabled()) {
            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent, FinalValue.REQUEST_ENABLE_BT);
        }
    }
    
    @Override
    protected void onResume() {
    	// TODO Auto-generated method stub
    	super.onResume();
    	// Get a set of currently paired devices
    	mNewDevicesSet.clear();
        setTitle("Scanning");
    	doDiscovery();
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();

        // Make sure we're not doing discovery anymore
        if(ble_scanning)
        {
            ble_scanning = false;
            mBtAdapter.stopLeScan(mLeScanCallback);
        }
    }

    /**
     * Start device discover with the BluetoothAdapter
     */
    final String service_uuid_gereric_access = "00001800-0000-1000-8000-00805f9b34fb";
    final String service_uuid_gereric_attribute = "00001801-0000-1000-8000-00805f9b34fb";
    final String service_uuid = "f000aa60-0451-4000-b000-000000000000"; 
    
    private void doDiscovery() {
        if (D) Log.d(TAG, "doDiscovery()");

        // Indicate scanning in the title
        setProgressBarIndeterminateVisibility(true);
        setTitle(R.string.scanning);

        // Turn on sub-title for new devices
//        findViewById(R.id.title_new_devices).setVisibility(View.VISIBLE);

        ble_scanning = true;
        UUID[] uuid_arrayUuids = new UUID[1]; 
        uuid_arrayUuids[0] = UUID.fromString(service_uuid);
//            { 
////                UUID.fromString(service_uuid_gereric_access), 
////                UUID.fromString(service_uuid_gereric_attribute), 
//        	UUID.fromString(service_uuid) 
//        };
        
        tv.setText(scanning);
        pb.setVisibility(View.VISIBLE);
        mBtAdapter.startLeScan(mLeScanCallback);
        mHandler.postDelayed(runnable, BLUETOOTH_SCAN_PERIOD);
        invalidateOptionsMenu();
    }
    
    final Runnable runnable = new Runnable() {            
        @Override
        public void run()
        {
            // TODO Auto-generated method stub
    	    mHandler.removeCallbacks(runnable);
            if(ble_scanning)
            {
                pb.setVisibility(View.INVISIBLE);
                tv.setText(choose);
                mBtAdapter.stopLeScan(mLeScanCallback);
                ble_scanning = false;                    
            }
            
            setProgressBarIndeterminateVisibility(false);
            setTitle(R.string.select_device);
            if (mNewDevicesSet.size() == 0) 
            {
                String noDevices = getResources().getText(R.string.none_found).toString();
                mNewDevicesSet.add(noDevices);
                newDevicesListViewClickable = false;
            }    
        }
    };
    
    private boolean ble_scanning = false;

    // The on-click listener for all devices in the ListViews
    private OnItemClickListener mDeviceClickListener = new OnItemClickListener() 
    {
        public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) 
        {
            // Cancel discovery because it's costly and we're about to connect
            if(newDevicesListViewClickable)
            {
                Log.d(TAG, "OnItemClickListener ble_scanning = " + ble_scanning);
            	if(ble_scanning)
            	{
            	    mBtAdapter.stopLeScan(mLeScanCallback);
            	}

                // Get the device MAC address, which is the last 17 chars in the View
                String info = ((TextView) v).getText().toString();
                String address = info.substring(info.length() - 17);
                
                Intent intent = new Intent();
                // Create the result Intent and include the MAC address
                if(HintActivity.isFirst){
                	intent.setClass(DeviceListActivity.this, RemoteActivity.class);
                	intent.putExtra(EXTRA_DEVICE_ADDRESS, address);
                	startActivity(intent);
                }else{
	                intent.putExtra(EXTRA_DEVICE_ADDRESS, address);
	                // Set result and finish this Activity
	                setResult(Activity.RESULT_OK, intent);
                }
                
                finish();
            } 
        }
    };
    
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
        case FinalValue.REQUEST_ENABLE_BT:
            if (resultCode == Activity.RESULT_OK) {
            	
            } else {
                Toast.makeText(this, R.string.bt_not_enabled_leaving, 
                		Toast.LENGTH_SHORT).show();
                finish();
            }
            break;
        }
    }

}
